package cn.hnbjx.prepaid.sdk;

import cn.hnbjx.prepaid.pojo.WxParameter;
import cn.hnbjx.prepaid.service.WxService;
import cn.hnbjx.prepaid.utils.MyX509TrustManager;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
public class WeixinUtil {
    @Autowired
    WxParameter wxParameter;

    @Autowired
    private WxService wxService;
    public static String doPost(String httpUrl, String param) {

        System.out.println(httpUrl);
        System.out.println(param);

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }


    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取jsapi_ticket
     *
     * @param
     * @param
     * @return
     */

    /**
     * 获取prepay_id
     *
     * @param
     * @param
     * @return
     */
    public String getprepay_id(BigDecimal price, String str, String openId) throws Exception {
        String appid = wxParameter.getmpAppId();
        String mch_id = wxParameter.getMchId();

        String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random RANDOM = new SecureRandom();
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        String nonce_str = new String(nonceChars);


        String body = "止动产品";
        String out_trade_no = str;
        String total_fee = price.stripTrailingZeros().toPlainString();
        System.out.println(total_fee+"-------total_fee-------");
        String spbill_create_ip = "127.0.0.1";
        String trade_type = "JSAPI";

        String notify_url = "https://" + wxParameter.getDomain() + "/success";

        Map<String, String> map = new HashMap<>();

        map.put("appid", appid);
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_str);
        map.put("body", body);
        map.put("out_trade_no", out_trade_no);
        map.put("total_fee", total_fee);
        map.put("spbill_create_ip", spbill_create_ip);
        map.put("trade_type", trade_type);
        map.put("notify_url", notify_url);
        map.put("openid", openId);
        System.out.println(map+wxParameter.getApikey());
        String sign = WXPayUtil.generateSignature(map, wxParameter.getApikey());
        System.out.println(sign+"----sign------");
        map.put("sign", sign);
        log.info("getprepay_id: {}", map);
        log.info("");
        // 获取公众号prepay_id的链接
        String prepayIdUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String xml = WXPayUtil.mapToXml(map);
        log.info("getprepay_id  xml: {}", xml);
        String post = doPost(prepayIdUrl, xml);
        Map<String, String> stringMap = WXPayUtil.xmlToMap(post);
        log.info("stringMap: {}", stringMap);
        // 如果请求成功
        if (null != post) {
            try {
                System.out.println("请求成功====");
                return stringMap.get("prepay_id");
            } catch (JSONException e) {
            }
        } else {
            System.out.println("未获取到prepay_id");
        }

        return null;
    }

    /**
     * 获取prepay_id
     *
     * @param
     * @param
     * @return
     */
    public String getprepay_id2(String weixin, BigDecimal price, String str, String openid) throws Exception {
        String appid = wxParameter.getmpAppId();
        String mch_id = wxParameter.getMchId();

        String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random RANDOM = new SecureRandom();
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        String nonce_str = new String(nonceChars);


        String body = weixin;
        String out_trade_no = str;
        String total_fee = price.stripTrailingZeros().toPlainString();
        String spbill_create_ip = "127.0.0.1";
        String trade_type = "JSAPI";

        String notify_url = "http://" + wxParameter.getDomain() + "/wx/success";

        Map<String, String> map = new HashMap<>();

        map.put("appid", appid);
        map.put("mch_id", mch_id);
        map.put("nonce_str", nonce_str);
        map.put("body", body);
        map.put("out_trade_no", out_trade_no);
        map.put("total_fee", total_fee);
        map.put("spbill_create_ip", spbill_create_ip);
        map.put("trade_type", trade_type);
        map.put("notify_url", notify_url);
        map.put("openid", openid);
        System.out.println(map+wxParameter.getApikey());
        String sign = WXPayUtil.generateSignature(map, wxParameter.getApikey());
        System.out.println(sign+"33333333333");
        map.put("sign", sign);
        log.info("getprepay_id: {}", map);
        // 获取公众号prepay_id的链接
        String prepayIdUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String xml = WXPayUtil.mapToXml(map);
        log.info("getprepay_id  xml: {}", xml);
        String post = doPost(prepayIdUrl, xml);
        Map<String, String> stringMap = WXPayUtil.xmlToMap(post);
        log.info("stringMap: {}", stringMap);
        // 如果请求成功
        if (null != post) {
            try {
                return stringMap.get("prepay_id");
            } catch (JSONException e) {
            }
        } else {
            System.out.println("未获取到prepay_id");
        }

        return null;
    }

    /**
     * 微信工具类
     */
    public static String httpRequest2(String requestUrl, String requestMethod, String output) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if (null != output) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            StringBuilder buffer = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
